package com.example.myphone;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
//import android.annotation.NonNull;
import androidx.annotation.NonNull;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView name;
    private TextView tel;
    private Button btnContacts;
    private Button btnCall;
    private Button btnSms;
    // 动态申请的应用权限集合
    private String[] permissions = new String[] {
            Manifest.permission.SEND_SMS,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    /**
     * 各个按钮点击时如何响应
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnContacts:
                contacts();
                break;
            case R.id.btnCall:
                call(tel.getText().toString());
                break;
            case R.id.btnSms:
                sms(tel.getText().toString());
                break;
        }
    }

    /**
     * onCreate 时，进行初始初始操作
     */
    private void init() {
        // 定位控件
        name = this.findViewById(R.id.name);
        tel = this.findViewById(R.id.tel);
        btnContacts = this.findViewById(R.id.btnContacts);
        btnCall = this.findViewById(R.id.btnCall);
        btnSms = this.findViewById(R.id.btnSms);

        // 添加监听事件
        btnContacts.setOnClickListener(this);
        btnCall.setOnClickListener(this);
        btnSms.setOnClickListener(this);
    }

    /**
     * 从通讯录中选择联系人，并在这步 动态申请应用权限
     *
     * 注意 动态申请应用权限 需要在 /app/manifests/AndroidManifest.xml 文件中 声明应用权限
     */
    @SuppressLint("IntentReset")
    private void contacts() {
//        Toast.makeText(MainActivity.this, "点击了 contacts", Toast.LENGTH_SHORT).show();
        getPermission();

        /*
         * 打开手机内置的 联系人Activity
         * 这里通过隐式打开，即通过添加一些属性来过滤出联系人Activity
         * */
        Intent intent = new Intent();
        // public static final String ACTION_PICK = "android.intent.action.PICK";
        intent.setAction(Intent.ACTION_PICK);
        // public static final String CATEGORY_DEFAULT = "android.intent.category.DEFAULT";
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/phone_v2"
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        // startActivityForResult() 参数 requestCode 0x30 表示 16进制的 30，即48
        startActivityForResult(intent, 0x30);

    }

    /**
     * 打电话
     * @param telephoneNum
     */
    private void call(String telephoneNum) {
//        Toast.makeText(MainActivity.this, "点击了 call", Toast.LENGTH_SHORT).show();
        /*
        * 打开手机内置的 电话Activity
        * 这里通过隐式打开，即通过添加一些属性来过滤出电话Activity
        * */
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri uri = Uri.parse("tel:" + telephoneNum);
        intent.setData(uri);
        startActivity(intent);
    }

    /**
     * 发短信
     * @param telephoneNum
     */
    private void sms(String telephoneNum) {
//        Toast.makeText(MainActivity.this, "点击了 sms", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("smsto:" + telephoneNum);
        intent.setData(uri);
        startActivity(intent);
    }

    /**
     * 动态申请权限
     */
    private void getPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 200);
        }
    }

    /**
     * 动态申请权限后的回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 200) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 已经获得授权
                Toast.makeText(MainActivity.this, "已经获得授权", Toast.LENGTH_SHORT).show();
            } else {
                // 未获得授权
                Toast.makeText(MainActivity.this, "授权被禁止了", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * activity 跳转后的回调方法
     */
    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x30) {
            /*
            * 读取用户点击的联系人信息
            * */
            Uri uri = null;
            if (data != null) {
                uri = data.getData();  // uri 值为 "content://com.android.contacts/data/1"
            }

            if (uri == null) {
                return;
            }
            Cursor cursor = null;
//            cursor = getContentResolver().query(uri, new String[]{"display_name", "data1"}, null, null, null);
            cursor = getContentResolver().query(uri, null, null, null,null);

            String username = null;
            String telNum =null;
            while (cursor.moveToNext()) {
                username = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                telNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            // 关闭 cursor
            cursor.close();
//                System.out.println("telNum ==: "+ telNum);
            if (telNum != null) {
                telNum = telNum.replaceAll("-", " ");
                telNum = telNum.replaceAll(" ", "");
            }
            // 更新 TextView 显示文本
            name.setText(username);
            tel.setText(telNum);
        }
    }

}